<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>创建博客</title>
    <style type="text/css">
        body {
            margin: 0 20px;
            line-height: 1;
        }
        a {
            text-decoration-line: none;
        }
        .title-wrapper {
            margin-bottom: 10px;
        }
        .title-wrapper input {
            width: 300px;
        }
        .content-wrapper textarea {
            width: 300px;
            height: 150px;
        }
    </style>
</head>
<body>
    <h1 style="border-bottom: 1px solid #ccc; padding-bottom: 10px;">创建博客</h1>
    <div>
        <div class="title-wrapper">
            <input id="text-title">
        </div>
        <div class="content-wrapper">
            <textarea id="text-content"></textarea>
        </div>
        <div>
            <button id="btn-create">创建</button>
        </div>
    </div>

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script>
        // 发送 post 请求
        function post(url, data = {}) {
            return $.ajax({
                type: 'post',
                url,
                data: JSON.stringify(data),
                contentType: "application/json",
            })
        }

        // 获取 dom 元素
        $textTitle = $('#text-title')
        $textContent = $('#text-content')
        $btnCreate = $('#btn-create')

        // 提交数据
        $btnCreate.click(() => {
            const title = $textTitle.val().trim()
            const content = $textContent.val().trim()
            if (title === '' || content === '') {
                alert('标题或内容不能为空')
                return
            }

            const url = '/api/blog/new'
            const data = {
                title,
                content
            }
            post(url, data).then(res => {
                if (res.errno !== 0) {
                    alert('操作错误')
                    return
                }
                alert('创建成功')
                location.href = '/admin.html'
            })
        })

    </script>
</body>
</html>